package com.mashibing.juc.c_026_00_interview.A1B2C3;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class T10_00_PipedStream {

    public static void main(String[] args) throws Exception {

        char[] chars1 = "1234567".toCharArray();
        char[] chars2 = "ABCDEFG".toCharArray();

        PipedInputStream input1 = new PipedInputStream();
        PipedInputStream input2 = new PipedInputStream();
        PipedOutputStream output1 = new PipedOutputStream();
        PipedOutputStream output2 = new PipedOutputStream();

        input1.connect(output1);
        input2.connect(output2);

        String token = "Your Turn";

        new Thread(() -> {
            byte[] buffer = new byte[9];
            try {
                for (char i : chars1) {
                    input1.read(buffer);
                    if (new String(buffer).equals(token)) {
                        System.out.print(i);
                    }
                    output2.write(token.getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            byte[] buffer = new byte[9];
            try {
                for (char c : chars2) {
                    output1.write(token.getBytes());
                    input2.read(buffer);
                    if (new String(buffer).equals(token)) {
                        System.out.print(c);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, "t2").start();

    }

}


